package com.turing.usdtpay.http;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Pair;


import com.turing.usdtpay.http.callback.ApiCallback;
import com.turing.usdtpay.http.entity.ResponseDate;
import com.turing.usdtpay.http.okhttp.OkHttpProxy;
import com.turing.usdtpay.http.okhttp.listener.UploadListener;
import com.turing.usdtpay.http.okhttp.model.Progress;
import com.turing.usdtpay.utils.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Response;

/**
 * Created by $Jay
 * Date : 2019\1\15
 **/
public class ApiService {
    public static final String REQ_TAG = "api_request : ";
    public static final String SIGN_TAG = "api_sign : ";
    public static final String REP_TAG = "api_response : ";

    //设置超时时间，单位秒
    private static final int API_CONNECT_TIMEOUT = 10;
    private static final int API_READ_TIMEOUT = 15;
    private static final int API_WRITE_TIMEOUT = 15;
    private static ApiService mApiService;

    private ApiService(){
        OkHttpClient build = OkHttpProxy.getInstance().newBuilder()
                .connectTimeout(API_CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(API_READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(API_WRITE_TIMEOUT, TimeUnit.SECONDS)
                .build();
        OkHttpProxy.setInstance(build);
    }

    private static ApiService init(){
        synchronized (ApiService.class){
            if (mApiService == null){
                mApiService = new ApiService();
            }
        }
        return mApiService;
    }

    public static ApiService getInstance(){ return mApiService == null?init():mApiService;}

    /**
     * get请求
     *
     * @param url      url，请求url地址
     * @param params   params，请求params，get请求拼接至url尾部
     * @param callback callback，请求回调
     */
    public void getRequest(String url, HashMap<String,String> params, ApiCallback callback){
        ApiWrapper.printDebugMsg(url,null,params);
        OkHttpProxy.get()
                .url(url)
                .setParams(params)
                .enqueue(ApiWrapper.wrapJsonOkCallBack(callback));
    }

    /**
     * post请求
     *
     * @param url      url，请求url地址
     * @param params   params，请求params，get请求拼接至url尾部
     * @param callback callback，请求回调
     */
    public void postRequest(String url, HashMap<String,String> params, ApiCallback callback){
        HashMap<String, String> wrapApiParams = ApiWrapper.wrapApiParams(params);
        ApiWrapper.printDebugMsg(url,null,wrapApiParams);
        OkHttpProxy.post()
                .url(url)
                .setParams(wrapApiParams)
                .enqueue(ApiWrapper.wrapJsonOkCallBack(callback));
    }


    /**
     * post请求
     *
     * @param url      url，请求url地址
     * @param params   params，请求params，get请求拼接至url尾部
     * @param callback callback，请求回调
     */
    public void postRequestWithCommmon(Context context, String url, HashMap<String,String> params, ApiCallback callback){
        HashMap<String, String> wrapApiParams = ApiWrapper.wrapApiParamsWithCommon(context,params);
        ApiWrapper.printDebugMsg(url,null,wrapApiParams);
        OkHttpProxy.post()
                .url(url)
                .setParams(wrapApiParams)
                .enqueue(ApiWrapper.wrapJsonOkCallBack(callback));
    }

    public void uploadFile(Context context, String url, HashMap<String,String> params, File file, final ApiCallback callback){
        HashMap<String, String> wrapApiParams = ApiWrapper.wrapApiParamsWithCommon(context,params);
        Pair<String,File> filePair = new Pair<>("file",file);
        ApiWrapper.printDebugMsg(url,null,wrapApiParams);
        OkHttpProxy.upload()
                .url(url)
                .setParams(wrapApiParams)
                .file(filePair)
                .start(new UploadListener() {
            @Override
            public void onSuccess(Response response) {
                LogUtils.d("onSuccess -->"+response);
                String json = "";
                try {
                    json = response.body().string();
                    LogUtils.d("onSuccessFilter  code--->"+response.code()+",json--->"+json);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    JSONObject object = jsonObject.optJSONObject("data");
                    String data = "";
                    if (object == null){
                        data = "";
                    }else {
                        data = object.toString();
                    }
                    LogUtils.d("data : -->"+data);
                    callback.onSuccess(response.code(),new ResponseDate(jsonObject.optInt("state"),data,jsonObject.optString("msg")));
                } catch (JSONException e) {
                    e.printStackTrace();
                    callback.onFailure(e);
                }
            }

            @Override
            public void onFailure(Exception e) {
                callback.onFailure(e);
            }

            @Override
            public void onUIProgress(Progress progress) {
                callback.onUIProgress((int) (((float)progress.getCurrentBytes())/((float) progress.getTotalBytes())*100));
            }
        });
    }

}
